package com.students.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.students.config.jwt.JwtTokenUtil;
import com.students.utils.AdminUtil;
import com.students.mapper.AdminMapper;
import com.students.mapper.AdminRoleMapper;
import com.students.mapper.RoleMapper;
import com.students.pojo.Admins;
import com.students.pojo.AdminRole;
import com.students.pojo.RespBean;
import com.students.pojo.Role;
import com.students.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author caohanqing
 * @since 2022-04-06
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admins> implements IAdminService {

    @Autowired(required = false)
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired(required = false)
    private RoleMapper roleMapper;
    @Autowired(required = false)
    private AdminRoleMapper adminRoleMapper;

    //登录之后返回token
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码错误，请重新输入验证码!");
        }
        //从数据库获取username
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if (null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号被禁用");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken=new
                UsernamePasswordAuthenticationToken(
                        userDetails,
                null,
                userDetails.getAuthorities()
        );
        //将对象放在全局
        SecurityContextHolder.getContext()
                .setAuthentication(authenticationToken);

        //登录成功,生成token
        String token=jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap=new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);//请求头

        return RespBean.success("登陆成功",tokenMap);
    }

    /*
    * 根据用户名获取用户信息
    * */
    @Override
    public Admins getAdminByUserName(String username) {

        return adminMapper.selectOne(
                new QueryWrapper<Admins>()
                        .eq("username",username)
                        .eq("enabled",true)
        );
    }

    @Override
    //根据用户id查询角色列表
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    //获取所有操作员
    @Override
    public List<Admins> getAllAdmins(String ketwords) {
        return adminMapper.getAllAdmins(
                AdminUtil.getCurrentAdmin()
                .getId(),ketwords
        );
    }

    //更新操作员角色
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(
                new QueryWrapper<AdminRole>()
        .eq("adminId",adminId));

        Integer integer = adminRoleMapper.updateAdminRole(adminId, rids);
        if (rids.length==integer){
            return RespBean.success("更新成功!");
        }
        return RespBean.error("更新失败!");
    }

    //更新用户密码
    @Override
    public RespBean updatePassword(String oldPass, String pass, Integer adminId) {
        Admins admin=adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        //判断旧密码是否正确，并更新密码
        if (encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(pass));
            int result=adminMapper.updateById(admin);
            if (1==result){
                return RespBean.success("更新成功!");
            }
        }
        return RespBean.error("更新失败！");
    }
}
